/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  DataAnalysisFragment.java   
 * @Package com.jiyi.activity.owner   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-21 上午11:20:53   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.jiyi.bean.owner.DataAnalysisJson;
import com.jiyi.bean.owner.DataAnalysisJson.WbCatList;
import com.jiyi.bean.owner.DataAnalysisJson.WbTimes;
import com.jiyi.bean.owner.DataAnalysisJson.WxCatList;
import com.jiyi.bean.owner.DataAnalysisJson.WxPrice;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.MyMarkerView;
import com.jiyi.view.MyPriceMarkerView;
import com.jiyi.widget.MyPriceAxisValueFormatter;
import com.jiyi.widget.MyTimeAxisValueFormatter;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: DataAnalysisFragment
 * @Description:TODO(数据分析)
 * @author: HYM
 * @date: 2017-9-21 上午11:20:53
 * 
 */
public class DataAnalysisFragment extends Fragment {

	public static String TAG = DataAnalysisFragment.class.getName();
	@BindView(R.id.lineChart)
	LineChart lineChart;
	@BindView(R.id.pieChart)
	PieChart pieChart;
	@BindView(R.id.priceLineChart)
	LineChart priceLineChart;
	@BindView(R.id.wxPieChart)
	PieChart wxPieChart;
	@BindView(R.id.rgCheck)
	RadioGroup rgCheck;
	@BindView(R.id.llWB)
	LinearLayout llWB;
	@BindView(R.id.llWX)
	LinearLayout llWX;

	@BindView(R.id.tvWBTimeTitle)
	TextView tvWBTimeTitle;
	@BindView(R.id.tvWBCatTitle)
	TextView tvWBCatTitle;
	@BindView(R.id.tvWxFxTitle)
	TextView tvWxFxTitle;
	@BindView(R.id.tvWXCatTitle)
	TextView tvWXCatTitle;

	LayoutInflater inflater;
	String company_id;

	List<WbTimes> wbTimes = new ArrayList<WbTimes>();
	List<WbCatList> wbCatLists = new ArrayList<WbCatList>();
	List<WxPrice> wxPrices = new ArrayList<WxPrice>();
	List<WxCatList> wxCatLists = new ArrayList<WxCatList>();

	// 查看的类型 1 维保的分析 2 维修的分析
	int type = 1;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_data_analysis,
				container, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		init();
		return view;
	}
	
	@Override
	public void onDestroy() {
		VolleyRequest.cancelRequest(TAG);
		super.onDestroy();
	}

	void init() {
		getNewsDate();
		getIntentData();
		getData();
		rgCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == R.id.rbWB) {
					llWB.setVisibility(View.VISIBLE);
					llWX.setVisibility(View.GONE);
				} else {
					llWB.setVisibility(View.GONE);
					llWX.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	private void getNewsDate() {
		Calendar c = Calendar.getInstance();
		int curYear = c.get(Calendar.YEAR);
		tvWBTimeTitle.setText(curYear+tvWBTimeTitle.getText().toString());
		tvWBCatTitle.setText(curYear+tvWBCatTitle.getText().toString());
		tvWxFxTitle.setText(curYear+tvWxFxTitle.getText().toString());
		tvWXCatTitle.setText(curYear+tvWXCatTitle.getText().toString());
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", company_id);

		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_OWNER_DATA_ANALYSIS, TAG, params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
//						if(SysUtils.checkActivityIsNotExist(getActivity()))
//						{
//							return;
//						}
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								DataAnalysisJson temp = new Gson().fromJson(
										result, DataAnalysisJson.class);
								wbTimes.clear();
								wbTimes.addAll(temp.getData().getWbTimes());
								wbCatLists.clear();
								wbCatLists
										.addAll(temp.getData().getWbCatList());
								wxPrices.clear();
								wxPrices.addAll(temp.getData().getWxPrice());
								wxCatLists.clear();
								wxCatLists
										.addAll(temp.getData().getWxCatList());
								initDataByType();
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void getIntentData() {
		company_id = getArguments().getString("company_id");
	}

	private void generateWbTime(List<WbTimes> temp) {

		ArrayList<Entry> e1 = new ArrayList<Entry>();

		for (int i = 1; i < 13; i++) {
			boolean hasData = false;
			for (int j = 0; j < temp.size(); j++) {
				if (i == temp.get(j).getMonth()) {
					e1.add(new Entry(i, temp.get(j).getCount()));
					hasData = true;
					break;
				}
			}
			if (!hasData) {
				e1.add(new Entry(i, 0));
			}
		}

		LineDataSet set2;
		set2 = new LineDataSet(e1, "2017年维护保养次数统计图");
		set2.setColor(Color.rgb(241, 171, 49));
		set2.setCircleColor(Color.rgb(241, 171, 49));
		set2.setLineWidth(1f);
		set2.setCircleRadius(3f);
		set2.setDrawValues(false);
//		set2.setHighlightEnabled(true);

		ArrayList<ILineDataSet> sets = new ArrayList<ILineDataSet>();
		sets.add(set2);

		LineData cd = new LineData(sets);

		MyMarkerView mv = new MyMarkerView(getContext(),
				R.layout.custom_marker_view);
		mv.setChartView(lineChart); // For bounds control
		lineChart.setMarker(mv); // Set the marker to the chart
		lineChart.getDescription().setEnabled(false);
		lineChart.setDrawGridBackground(false);
		lineChart.setDrawBorders(false);
		lineChart.setNoDataText("没有数据");
		lineChart.setTouchEnabled(true);
		lineChart.setDragEnabled(false);
		lineChart.setScaleEnabled(false);
		lineChart.setPinchZoom(false);
		lineChart.setBackgroundColor(Color.WHITE);
		lineChart.getLegend().setEnabled(false);

		// IAxisValueFormatter iAxisValueFormatter = new YearXAxisFormatter();
		XAxis xAxis = lineChart.getXAxis();
		xAxis.setPosition(XAxisPosition.BOTTOM);
		xAxis.setDrawGridLines(false);
		xAxis.setDrawAxisLine(false);
//		xAxis.setYOffset(8);
		// xAxis.setValueFormatter(iAxisValueFormatter);

		IAxisValueFormatter custom = new MyTimeAxisValueFormatter();
		YAxis leftAxis = lineChart.getAxisLeft();
		leftAxis.setLabelCount(5, false);

		leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
		leftAxis.setDrawAxisLine(false);
		leftAxis.setXOffset(10);
		leftAxis.setGridColor(Color.parseColor("#F5E7CF"));
		leftAxis.setValueFormatter(custom);
		leftAxis.setGranularity(1);

		YAxis rightAxis = lineChart.getAxisRight();
		rightAxis.setEnabled(false);

		// set data
		lineChart.setData(cd);

		// do not forget to refresh the chart
		// holder.chart.invalidate();
		lineChart.animateX(750);
		// return cd;
	}

	private void generateWbCat(List<WbCatList> temp) {

		ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
		ArrayList<Integer> colors = new ArrayList<Integer>();

		for (int i = 0; i < temp.size(); i++) {
			colors.add(getRandColorCode());
			entries.add(new PieEntry((float) (temp.get(i).getCount()), temp
					.get(i).getName()));
		}

		PieDataSet d = new PieDataSet(entries, "");

		// space between slices
		d.setSliceSpace(2f);
		d.setColors(colors);
//		d.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
//		d.setValueLinePart1OffsetPercentage(80.f);
//		d.setValueLinePart1Length(0.2f);
//		d.setValueLinePart2Length(0.4f);

		PieData cd = new PieData(d);
		cd.setValueFormatter(new PercentFormatter());
		pieChart.setBackgroundColor(Color.WHITE);
		pieChart.setUsePercentValues(true);
		pieChart.getDescription().setEnabled(false);

		pieChart.setDrawHoleEnabled(true);
		pieChart.setHoleColor(Color.WHITE);

		pieChart.setTransparentCircleColor(Color.WHITE);
		pieChart.setTransparentCircleAlpha(110);

		pieChart.setHoleRadius(58f);
		pieChart.setTransparentCircleRadius(61f);

		pieChart.setRotationEnabled(true);
		pieChart.setHighlightPerTapEnabled(true);
//		pieChart.setEntryLabelColor(Color.BLACK);
//		pieChart.highlightValue(null);

		// pieChart.setMaxAngle(180f); // HALF CHART
		// pieChart.setRotationAngle(180f);
		pieChart.setDrawSliceText(false);
		Legend mLegend = pieChart.getLegend(); // 设置比例图
		mLegend.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT); // 左下边显示
		mLegend.setFormSize(12f);// 比例块字体大小
		mLegend.setXEntrySpace(2f);// 设置距离饼图的距离，防止与饼图重合
		mLegend.setYEntrySpace(2f);
		// 设置比例块换行...
		mLegend.setWordWrapEnabled(true);
		mLegend.setForm(Legend.LegendForm.SQUARE);// 设置比例块形状，默认为方块
		// do not forget to refresh the chart
		// holder.chart.invalidate();
		// set data
		pieChart.setData(cd);

		pieChart.animateY(900);

	}

	private void generateWxPrice(List<WxPrice> temp) {

		ArrayList<Entry> e1 = new ArrayList<Entry>();

		for (int i = 1; i < 13; i++) {
			boolean hasData = false;
			for (int j = 0; j < temp.size(); j++) {
				if (i == temp.get(j).getMonth()) {
					e1.add(new Entry(i, temp.get(j).getPrice()));
					hasData = true;
					break;
				}
			}
			if (!hasData) {
				e1.add(new Entry(i, 0));
			}
		}

		LineDataSet set2;
		set2 = new LineDataSet(e1, "2017年报修分析表");
		set2.setColor(Color.rgb(241, 171, 49));
		set2.setCircleColor(Color.rgb(241, 171, 49));
		set2.setLineWidth(1f);
		set2.setCircleRadius(3f);
		set2.setDrawValues(false);
//		set2.setHighlightEnabled(true);

		ArrayList<ILineDataSet> sets = new ArrayList<ILineDataSet>();
		sets.add(set2);

		LineData cd = new LineData(sets);

		MyPriceMarkerView mv = new MyPriceMarkerView(getContext(),
				R.layout.custom_marker_view);
		mv.setChartView(priceLineChart); // For bounds control
		priceLineChart.setMarker(mv); // Set the marker to the chart
		priceLineChart.getDescription().setEnabled(false);
		priceLineChart.setDrawGridBackground(false);
		priceLineChart.setDrawBorders(false);
		priceLineChart.setNoDataText("没有数据");
		priceLineChart.setTouchEnabled(true);
		priceLineChart.setDragEnabled(false);
		priceLineChart.setScaleEnabled(false);
		priceLineChart.setPinchZoom(false);
		priceLineChart.setBackgroundColor(Color.WHITE);
		priceLineChart.getLegend().setEnabled(false);

		// IAxisValueFormatter iAxisValueFormatter = new YearXAxisFormatter();
		XAxis xAxis = priceLineChart.getXAxis();
		xAxis.setPosition(XAxisPosition.BOTTOM);
		xAxis.setDrawGridLines(false);
		xAxis.setDrawAxisLine(false);
//		xAxis.setYOffset(8);
		// xAxis.setValueFormatter(iAxisValueFormatter);

		IAxisValueFormatter custom = new MyPriceAxisValueFormatter();
		YAxis leftAxis = priceLineChart.getAxisLeft();
		leftAxis.setLabelCount(5, false);

		leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
		leftAxis.setDrawAxisLine(false);
		leftAxis.setXOffset(10);
		leftAxis.setGridColor(Color.parseColor("#F5E7CF"));
		leftAxis.setValueFormatter(custom);
		leftAxis.setGranularity(1);

		YAxis rightAxis = priceLineChart.getAxisRight();
		rightAxis.setEnabled(false);

		// set data
		priceLineChart.setData(cd);

		// do not forget to refresh the chart
		// holder.chart.invalidate();
		priceLineChart.animateX(750);
		// return cd;
	}

	private void generateWxCat(List<WxCatList> temp) {

		ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
		ArrayList<Integer> colors = new ArrayList<Integer>();

		for (int i = 0; i < temp.size(); i++) {
			colors.add(getRandColorCode());
			entries.add(new PieEntry((float) (temp.get(i).getCount()), temp
					.get(i).getName()));
		}

		PieDataSet d = new PieDataSet(entries, "");

		// space between slices
		d.setSliceSpace(2f);
		d.setColors(colors);

		PieData cd = new PieData(d);
		cd.setValueFormatter(new PercentFormatter());
		wxPieChart.setBackgroundColor(Color.WHITE);
		wxPieChart.setUsePercentValues(true);
		wxPieChart.getDescription().setEnabled(false);

		wxPieChart.setDrawHoleEnabled(true);
		wxPieChart.setHoleColor(Color.WHITE);

		wxPieChart.setTransparentCircleColor(Color.WHITE);
		wxPieChart.setTransparentCircleAlpha(110);

		wxPieChart.setHoleRadius(58f);
		wxPieChart.setTransparentCircleRadius(61f);

		wxPieChart.setRotationEnabled(true);
		wxPieChart.setHighlightPerTapEnabled(true);

		// pieChart.setMaxAngle(180f); // HALF CHART
		// pieChart.setRotationAngle(180f);
		wxPieChart.setDrawSliceText(false);
		Legend mLegend = wxPieChart.getLegend(); // 设置比例图
		mLegend.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT); // 左下边显示
		mLegend.setFormSize(12f);// 比例块字体大小
		mLegend.setXEntrySpace(2f);// 设置距离饼图的距离，防止与饼图重合
		mLegend.setYEntrySpace(2f);
		// 设置比例块换行...
		mLegend.setWordWrapEnabled(true);
		mLegend.setForm(Legend.LegendForm.SQUARE);// 设置比例块形状，默认为方块
		// do not forget to refresh the chart
		// holder.chart.invalidate();
		// set data
		wxPieChart.setData(cd);

		wxPieChart.animateY(900);

	}

	void initDataByType() {
		if (wbTimes!= null && wbTimes.size()>0) {
			generateWbTime(wbTimes);
		}
		if (wbCatLists!= null && wbCatLists.size()>0) {
			generateWbCat(wbCatLists);
		}
		if (wxPrices!= null && wxPrices.size()>0) {
			generateWxPrice(wxPrices);
		}
		if (wxCatLists!= null && wxCatLists.size()>0) {
			generateWxCat(wxCatLists);
		}
		
	}

	/**
	 * 获取十六进制的颜色代码.例如 "#6E36B4" , For HTML ,
	 * 
	 * @return String
	 */
	public static int getRandColorCode() {
		Random random = new Random();
		int ranColor = 0xff000000 | random.nextInt(0x00ffffff);
		return ranColor;
	}

}
